﻿using Dyao.Book.Application.Abstractions;
using Dyao.Book.Core;
using Foundation.Core;

namespace Dyao.Book.Application
{
    [TaskCenterRuleName(RuleKey, DisplayName = "验证用户任务时间间隔")]
    public class UserTaskIntervalExcutor : TaskRuleExcutorBase, ITaskRuleExcutor<UserTaskIntervalExcutorModel>, ITaskRuleSettingsLoader, ITransientDependency
    {
        public const string RuleKey = TaskCenterRuleExcutorKeyInfo.UserTaskIntervalKey;
        private UserTaskIntervalExcutorModel _setting;
        private readonly ITaskCenterRecordApplication _taskCenterRecordService;

        public UserTaskIntervalExcutor(TaskCenterRecordApplication taskCenterRecordService)
        {
            this._taskCenterRecordService = taskCenterRecordService;
        }

        public override string Key => RuleKey;

        public UserTaskIntervalExcutorModel Settings => _setting;

        public override async Task ExcuteAsync(TaskCenterRuleExcutingContext context)
        {
            if (_setting == null) return;

            var haveRecord = await _taskCenterRecordService.HaveRecordAsync(context.TaskCode, _setting.IntervalSeconds);
            if (haveRecord)
            {
                throw new BusinessException(CommonExceptionCode.TaskCenterUserOperateRuleOften, $"操作太频繁({_setting.IntervalSeconds}s)");
            }
        }

        public void LoadSettings(string settingsStr)
        {
            _setting = Deserialize<UserTaskIntervalExcutorModel>(settingsStr);
        }
    }
}
